#!/bin/env python
#-*- coding:utf-8 -*-

#----------------------------------------------------------------------------
# Name     :      start.py
# Purpose  :      gui starter, include app module and splash code.
# Author   :      Albert cheng
# Created  :      2012-10-29
# Copyright:     (c) 2012 by Albertcheng
# Licence  :      wxWindows license
#----------------------------------------------------------------------------


import wx
from dbo import *
from gui_grid import *





class DataConfigDialog(wx.Dialog):
    
    def __init__(self,proj,title,fn,tag,md,key,db,p_id,Tags,chd): 
        
        #title -- dialog's header text
        # fn   -- xml's argus
        # tag  -- xml's argus       
        # md   -- mysql's data
        # sd   -- sqls' data
        # key  -- key word for sqls' data
        # db   -- used database name
        # p_id -- player id
        # Tags -- gui's tag names
        
        
        self.getxml = get_sql()
        config = self.getxml.getxml(fn,tag)
        
        self.sd = self.getxml.get()[proj][key]
        
        self.p_id = p_id
        self.db = db
        self.md = md
        self.cfg = []
        self.key = key
        #Tags = ["是否生成","道具名","道具数量"]
        
        for x in config:
            idx = x[0]
            name = x[1]
            isbool = 0
            self.cfg.append([isbool,name.decode("utf-8"),idx])
        
        
        wx.Dialog.__init__(self, None, -1, title, style=wx.CAPTION|wx.CLOSE_BOX)
        about   = wx.StaticText(self, -1, "欢迎使用离子战锤工作室的mysql工具.\n修改方法：\n1. 双击要修改道具、技能、武器所在行对应的等级/数量的空格\n2. 打开下拉框选择数据，然后点确认即可）".decode("utf-8"))

        sizer = wx.BoxSizer(wx.VERTICAL)

        self.griddata = [[x[0],x[1],'0'] for x in self.cfg]
        
        
        
        self.g = self.__make_grid_code(Tags,self.griddata,chd)
        
        self.g.SetMinSize((350,400))
        

        confirm = wx.Button(self,-1,"确认提交".decode("utf-8"))
        


        self.Bind(wx.EVT_BUTTON,self.OnConfirm,confirm)

        sizer.Add(about,0,wx.EXPAND,5)
        sizer.Add(wx.StaticLine(self,-1,size=(100,1)),0,wx.EXPAND,5)
        sizer.Add(self.g,0,wx.EXPAND,5)
        sizer.Add(confirm,0,wx.EXPAND|wx.ALIGN_CENTER,5)
        self.SetSizer(sizer)
        sizer.Fit(self)
        self.Centre()
        
        
        
        
        
    def __make_grid_code(self,Tags,data,chd):
        colsize = [(0,80),
                   (1,110),
                   (2,80),
                   #(3,80)
                   ]
                
                
        dt = [
              GRID_BOOL,
              GRID_STRING,
              GRID_CHOICE+chd
              ]
        return CustTableGrid(self,Tags,dt,colsize,data)

    def OnConfirm(self,e):
        
        #=======================================================================
        # step 1: get data list from gui and mysql
        #=======================================================================
        sqls = []
        
        #=======================================================================
        # step 2: find out the repeat ids in mysql data and add the data into dellist
        #=======================================================================
        prop_id_idx = 3# for project ssdz
        prop_cnt_idx = 2
        dellist = []
        clear_id = {}
        #a = [x[3] for x in self.md]
        
        for nd in self.md:
            loop_id = int(nd[prop_id_idx])
            if loop_id not in clear_id.keys():
                clear_id[int(loop_id)] = nd
            else:
                old_cnt = clear_id[int(loop_id)][prop_cnt_idx]
                new_cnt = nd[prop_cnt_idx]
                
                if new_cnt > old_cnt:
                    dellist.append(clear_id[loop_id][0])
                    clear_id[int(loop_id)] = nd
                else:
                    dellist.append(nd[0])    
        
        for n in dellist:
            sql =  self.sd[3] % (self.db,n)
            sqls.append(sql)
            
        
        
        #=======================================================================
        # step 3: check out if the data from gui is in the mysql data, if not ,insert it, otherwise, update it
        #=======================================================================
        
        for n in range(len(self.cfg)):
            self.cfg[n][0] = self.g.GetValue(n,0)
            cnt = self.g.GetValue(n,2)
            self.cfg[n].append(cnt)
        
        k = [int(x) for x in clear_id.keys()]
        
        for n_gui_d in self.cfg:
            #print n_gui_d
            isbool = n_gui_d[0]
            idx = n_gui_d[2]
            cnt = n_gui_d[3]
            if int(isbool) == 1:
                
                if int(idx) in k:
                    data_idx = clear_id[int(idx)][0]
                    sql = self.sd[1] % (self.db,cnt,data_idx)
                else:
                    if self.key == "weapon":
                        sql = self.sd[2] % (self.db,idx,cnt,self.p_id)
                    else:
                        sql = self.sd[2] % (self.db,cnt,idx,self.p_id)
                sqls.append(sql)
        
        if sqls != []:
            self.s = sdbo()
            
            self.dbh =  DBO(self.s.showalldata()[0])
            #print sqls
            try:
                self.dbh.dosql(sqls)
                wx.MessageBox("Data Applied Successfully.", "SSSSSS", wx.OK)
                self.Destroy()
                
            except MySQLdb.Error,e:
                self.Log.log(e[1])
                wx.MessageBox("Data Applied Failed.\n"+e[1], "FFFFFFFFF", wx.OK)
                self.Destroy()
            return
